from odoo import models, _
from odoo.exceptions import UserError


class IrActionsReport(models.Model):
    _inherit = 'ir.actions.report'

    def _render_qweb_pdf(self, report_ref, res_ids=None, data=None):
        result = super()._render_qweb_pdf(report_ref, res_ids, data)
        self._create_print_recoed(report_ref, res_ids)

        return result

    def _create_print_recoed(self, report_ref, res_ids):
        report = self._get_report(report_ref)
        if report_ref == 'pcbmanufact.report_production_instruction_view' and not self.env.user.has_group('pcbmanufact.group_s_mrp_plan'):
            raise UserError(_('You are not authorized to print this template (%s)', report_ref))
        create_list = []
        for i in res_ids:
            create_list.append({
                'model_name': report.model,
                'record_id': i,
                'user_id': self.env.user.id,
                'print_template_name': report_ref
            })

        model = self.env[report.model]
        if hasattr(model, 's_printed'):
            self.env[report.model].browse(res_ids).write({'s_printed': True})

        self.env['s.print.record'].sudo().create(create_list)